﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.Diagnostics;
using System.Security.Permissions;

//[assembly:UIPermission(SecurityAction.RequestOptional,Unrestricted=true)]
[assembly:EventLogPermissionAttribute(SecurityAction.RequestMinimum, Unrestricted=true)]
// this one seems to have no effect when starting the application.
namespace EventLogEntryMaker
{
    public partial class frmMain : Form
    {
        public frmMain()
        {
            InitializeComponent();
        }

        private void cmdWriteMsgToLog_Click(object sender, EventArgs e)
        {
            const string source = "EventLogEntryMaker";

            string log;
            EventLogEntryType entryType;

            if (optApplicationLog.Checked)
            {
                log = "Application";
            }
            else
            {
                //TODO: Check why setting log = "System" write to Application.               
                log = "System";
            }

            if (optError.Checked)
            {
                entryType = EventLogEntryType.Error;
            }
            else
            {
                if (optWarning.Checked)
                {
                    entryType = EventLogEntryType.Warning;
                }
                else
                {
                    entryType = EventLogEntryType.Information;
                }
            }

            try
            {

                if (!EventLog.SourceExists(source))
                    // to avoid security problem, I started directly the app from the explorer
                    // as administrator.
                    // Now, I don't have this problem from VS anymore. ... strange
                {
                    EventLog.CreateEventSource(source, log);
                }
                EventLog el = new EventLog();
                el.Source = source;
                el.WriteEntry(this.txtEventMessage.Text, entryType);

            }
            catch (System.Security.SecurityException se)
            {
                System.Windows.Forms.MessageBox.Show("Write operation failed." + Environment.NewLine + "This application must be run with administrative privileges.");
            }

        }

     }
}
